import {MinHeap} from "./MinHeap.js";

export default class EventQueue<T = any> {
	_time: number;
	_events: MinHeap<T>;

	/**
	 * @class Generic event queue: stores events and retrieves them based on their time
	 */
	constructor() {
		this._time = 0;
		this._events = new MinHeap();
	}

	/**
	 * @returns {number} Elapsed time
	 */
	getTime() { return this._time; }

	/**
	 * Clear all scheduled events
	 */
	clear() {
		this._events = new MinHeap();
		return this;
	}

	/**
	 * @param {?} event
	 * @param {number} time
	 */
	add(event: T, time: number) {
		this._events.push(event,time);
	}

	/**
	 * Locates the nearest event, advances time if necessary. Returns that event and removes it from the queue.
	 * @returns {? || null} The event previously added by addEvent, null if no event available
	 */
	get() {
		if (!this._events.len()) { return null; }

		let { key: time, value: event } = this._events.pop();
		if (time > 0) { /* advance */
			this._time += time;
			this._events.shift(-time);
		}

		return event;
	}

	/**
	 * Get the time associated with the given event
	 * @param {?} event
	 * @returns {number} time
	 */
	getEventTime(event: T) {
		const r = this._events.find(event);
		if (r) {
			const { key } = r;
			return key;
		}
		return undefined;
	}

	/**
	 * Remove an event from the queue
	 * @param {?} event
	 * @returns {bool} success?
	 */
	remove(event: T) {
		return this._events.remove(event);
	};
}

